package com.woniuxy.realm;

import com.woniuxy.entity.Coach;
import com.woniuxy.entity.User;
import com.woniuxy.service.CoachService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;
/**
 * 吴毛伟原生态制造
 */
public class CoachRealm extends AuthorizingRealm {
    @Autowired
    private CoachService coachService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> roles = new HashSet<>();
        roles.add("coach");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        CustomizedToken customizedToken = (CustomizedToken) token;
        String cname = customizedToken.getUsername();
        Coach coachByCname = coachService.findCoachByCname(cname);
        if (coachByCname == null) {
            throw new UnknownAccountException("教练不存在！");
        }
        String principal = cname;
        String credentials = new SimpleHash("MD5", coachByCname.getPwd(), cname, 1024).toString();
        String realmName = getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials,
                realmName);
        return info;
    }
}
